package com.zzy.chapter4.decorator;

import com.zzy.chapter4.pojo.Order;
import com.zzy.chapter4.pojo.Products;
import com.zzy.chapter4.repo.ProductsRepository;
import com.zzy.chapter4.service.IOrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class OrderServiceDecorator extends AbstractOrderServiceDecorator{

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ProductsRepository productsRepository;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //@Value("${delay.service.time}")
    private String delayServiceTime;

    @Override
    public void setOrderService(IOrderService orderService) {
        this.orderService = orderService;
    }

    @Override
    protected void updateScoreAndSendRedPaper(String productId, int serviceLevel, float price) {
        switch (serviceLevel) {
            case 0:
                int score = Math.round(price / 100);
                System.out.println("正常处理，为用户更新积分！");
                Products products = productsRepository.findByProductId(productId);
                if(Objects.nonNull(products)) {
                    System.out.println("正常处理，为用户发红包！");
                }
                break;
            case 1:
                MessageProperties messageProperties = new MessageProperties();
                messageProperties.setExpiration(delayServiceTime);
                Message message = new Message(productId.getBytes());
                rabbitTemplate.send("normalExchange", "myRKey", message);
                System.out.println("延迟处理，发送消息到延迟交换机！时间=" + delayServiceTime);
                break;
            case 2:
                System.out.println("暂停服务，不处理！");
                break;
            default:
                throw new UnsupportedOperationException("Service Level Error");
        }
    }

    public Order decoratorPay(String orderId, int serviceLevel, float price) {
        Order order = super.payOrder(orderId);
        try{
            this.updateScoreAndSendRedPaper(order.getProductId(), serviceLevel, price);
        } catch (Exception e){
            // 重试机制
        }
        return order;
    }

    @Override
    public void friendPay(String sourceCustomer, String orderId, String targetCustomer, String payResult, String role) {
        this.orderService.friendPay(sourceCustomer, orderId, targetCustomer, payResult, role);
    }
}
